<template>
  <div id="printArea" ref="printArea" style="padding: 0 0 0 0">
    <div
      v-for="(citem, cindex) in bloods"
      :key="cindex"
      :ref="
        (el) => {
          if (el) printAreaRefs[cindex] = el
        }
      "
      class="printDiv"
      style="margin-bottom: 0; margin-left: 0; page-break-after: always"
    >
      <div class="t d-flex">
        <div class="t-l text-align-center">
          <div class="t-l-1 d-flex flex-column">
            <vue-barcode
              :display-value="false"
              :height="height"
              :margin="0.8"
              :value="substr(citem.id_out, 0, 14)"
              :width="1.2"
            >
              原始血袋号
            </vue-barcode>
            <div>
              <span class="font12">
                {{ substr(citem.id_out, 0, 5) }}
              </span>
              <span class="font12">
                {{ substr(citem.id_out, 5, 2) }}
              </span>
              <b class="font12">
                {{ substr(citem.id_out, 7, 7) }}
              </b>
              <span
                class="font12 text-align-center"
                style="
                  display: inline-block;
                  padding: 2px 3px;
                  margin-right: 1px;
                  border: 1px solid #999;
                "
              >
                {{ substr(citem.id_out, 14, 1) }}
              </span>
              <span
                class="font12 text-align-center"
                style="
                  display: inline-block;
                  padding: 2px 3px;
                  margin-right: 1px;
                  border: 1px solid #999;
                "
              >
                {{ substr(citem.id_out, 15, 1) }}
              </span>
              <span
                class="font12 text-align-center"
                style="
                  display: inline-block;
                  padding: 2px 3px;
                  border: 1px solid #999;
                "
              >
                {{ substr(citem.id_out, 16, 1) }}
              </span>
            </div>
            <b class="font12">{{ bloodPrint.hospital.name }}</b>
            <b class="font12">{{ bloodPrint.hospital.nameShort }}</b>
            <span class="font12">{{ bloodPrint.hospital.descri }}</span>
          </div>
          <div class="t-l-2 d-flex flex-column" style="margin-top: 4px">
            <div style="height: 36px">
              <vue-barcode
                :display-value="false"
                :height="height"
                :margin="0.8"
                :value="citem.id"
                :width="1.5"
              >
                血袋号
              </vue-barcode>
            </div>
            <b class="font18">{{ citem.id }}</b>
            <span v-if="citem.pid" class="font11">
              制备前血袋号：{{ citem.pid }}
            </span>
          </div>
          <div class="t-l-3 d-flex flex-column">
            <vue-barcode
              :display-value="false"
              :height="height"
              :margin="1"
              :value="
                (citem && citem.product_code) || bloodPrint.aboRhd.product_code
              "
              :width="1.1"
            >
              血液成分码
            </vue-barcode>
            <span class="text-align-left">
              {{
                (citem && citem.product_code) || bloodPrint.aboRhd.product_code
              }}
            </span>
            <b class="font14 mb4 mt4">
              {{ (citem.product && citem.product.name) || '' }}
            </b>
            <span class="font14">
              血量：{{ (+citem.capacity).toFixed(1) }}U
            </span>
          </div>
        </div>
        <div class="t-r">
          <div
            class="t-r-1 d-flex flex-column align-items-center text-align-center"
          >
            <template v-if="citem.rhd === '阳性'">
              <b class="font64">
                {{ citem.abo }}
              </b>
            </template>
            <template v-else>
              <img alt="" :src="`/img/${citem.abo}.png`" />
            </template>
            <b
              class="pd4 mb4"
              :class="citem.rhd === '阴性' ? 'bg-black color-white' : ''"
              style="display: inline-block; -webkit-print-color-adjust: exact"
            >
              RH(D){{ citem.rhd }}
            </b>
            <vue-barcode
              :display-value="false"
              :height="height"
              :margin="1"
              :value="(citem && citem.abo_code) || bloodPrint.aboRhd.code"
              :width="2"
            >
              血型RHD码
            </vue-barcode>
            <span>
              {{ (citem && citem.abo_code) || bloodPrint.aboRhd.code }}
            </span>
          </div>
          <div class="h8"></div>
          <div class="t-r-2 d-flex flex-column">
            <span class="font12">
              采血时间:
              <b>
                {{
                  (citem.collect_time && citem.collect_time.substr(0, 16)) || ''
                }}
              </b>
            </span>
            <div class="h8"></div>
            <span class="font12">
              制备时间:
              <b v-if="citem.preFrom">
                {{
                  (citem.preFrom &&
                    citem.preFrom.created_at &&
                    citem.preFrom.created_at.substr(0, 16)) ||
                  ''
                }}
              </b>
              <b v-if="citem.subFrom">
                {{
                  (citem.subFrom &&
                    citem.subFrom.created_at &&
                    citem.subFrom.created_at.substr(0, 16)) ||
                  ''
                }}
              </b>
            </span>
            <div class="h8"></div>
            <span class="font12">
              失效时间:
              <b>
                {{
                  (citem.invalid_time && citem.invalid_time.substr(0, 16)) || ''
                }}
              </b>
            </span>
            <div class="h8"></div>
            <vue-barcode
              :display-value="false"
              :height="height"
              :margin="0.8"
              :value="getInvalidCode(citem)"
              :width="1.2"
            >
              失效时间码
            </vue-barcode>
            <div class="h8"></div>
            <span class="font12">
              储存：{{
                (citem.product && citem.product.temperature_self) || ''
              }}
            </span>
          </div>
        </div>
      </div>
      <div class="h9"></div>
      <div class="b d-flex align-items-center">
        <div
          v-for="(item, index) in 2"
          :key="index"
          class="b-c text-align-center"
        >
          <span class="mr4">{{ citem.donor_id }}</span>
          <span>{{ getBloodUser(citem) }}</span>
          <vue-barcode
            :display-value="false"
            :height="height"
            :margin="0.8"
            :value="citem.tube_number"
            :width="1.2"
          >
            {{ citem.tube_number }}
          </vue-barcode>
          <b :class="getClass(citem)">
            {{ citem.tube_number }} {{ citem.abo }} {{ citem.rhd }}
          </b>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import VueBarcode from 'vue-barcode'
  import { doPrints, all } from '@/api/blood'
  import { mapGetters } from 'vuex'
  import { getLodop } from '@/utils/LodopFuncs'
  import { isArray } from 'lodash'
  import { toPng } from 'html-to-image'
  export default {
    components: {
      VueBarcode,
    },
    data() {
      return {
        printAreaRefs: [],
        title: '打印',
        blood: {},
        height: 29,
        bloodPrint: {
          hospital: {
            name: '中国人民解放军总医院',
            nameShort: '第一医学中心',
            code: '00000210012349',
            descri: '卫血站字[2012]第1号',
          },
          id: '02116274',
          capacity: 2,
          product: {
            name: '辐照去白RH(D)阴性机采血小板',
            code: 'B0011V00',
          },
          aboRhd: {
            abo: 'AB',
            rhd: '阴性',
            code: '8400',
          },
          time: {
            collect: '2021-08-02 13:30',
            pre: '2021-08-02 13:30',
            invalid: '2021-08-02 13:30',
            invalid_code: '0272051451',
          },
        },
        bloods: [],
      }
    },
    computed: {
      ...mapGetters(['printType', 'systemSet']),
    },
    methods: {
      getInvalidCode(item) {
        this.blood = item
        if (this.blood) {
          if (this.blood.invalid_time_code) {
            return this.blood.invalid_time_code
          }
          if (this.blood.invalid_time) {
            return this.blood.invalid_time.substr(0, 10).replace('-', '')
          }
        }
        return ''
      },
      getClass(blood) {
        if (blood && blood.abo === 'AB') {
          return 'font15'
        }
        return 'font16'
      },
      async doPrints() {
        const { msg } = await doPrints(this.bloods.map((val) => val.id))
        this.$emit('getAll')
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
      },
      getBloodUser(blood) {
        if (blood.blood_user) {
          return blood.blood_user
        }
        if (blood.id_out) {
          return blood.id_out.replace('=', '').substr(5, 8)
        }
        return ''
      },
      substr(str, start, length) {
        if (str && str.length > 0) {
          return str.substr(start, length)
        }
        return ''
      },
      show(row) {
        const ids = row.map((val) => val.id)
        this.all(ids)
      },
      async all(ids) {
        const { data } = await all(ids)
        this.bloods = data
        console.log('***********')
        console.log(this.bloods[0])
        console.log('***********')
        if (this.printType === 'silent') {
          this.$nextTick(() => {
            const strHtmls = []
            this.printAreaRefs.forEach((el) => {
              const barcodeElements = el.querySelectorAll(
                '.vue-barcode-element'
              )
              barcodeElements.forEach(async (barcodeElement) => {
                try {
                  const dataUrl = await toPng(barcodeElement, { quality: 1 })
                  const img = document.createElement('img')
                  img.src = dataUrl
                  barcodeElement.parentNode.replaceChild(img, barcodeElement)
                } catch (error) {
                  console.error('Error converting barcode to image:', error)
                }
              })

              strHtmls.push(el.innerHTML)
              if (strHtmls.length === this.bloods.length) {
                const elStyle = `#printArea {width: 306px;color: #111;}.t-l {width: 155px;}.t-r {width: 151px;}.b-c {width: 151px;}.d-flex{display:flex;}.align-items-center{align-items:center;}.flex-column{flex-direction:column;}.font12{font-size:12px !important;;}.font18{font-size: 18px !important;}.font11{font-size: 11px !important;}.text-align-center{text-align:center;}.h8{height:8px;}.font64 {
      font-size: 64px !important;
  }
  .pd4 {
      padding: 4px;
  }
  .mb4 {
      margin-bottom: 4px;
  }
  .mr4 {
      margin-right: 4px;
  }
  .font16 {
      font-size: 16px !important;
  }
  .stroke {
      margin-bottom: -4px;
      color: transparent;
      -webkit-text-stroke: 4px #000;
      -moz-text-stroke: 4px #000;
  }
  .bg-black {
      background: #000 !important;
  }
  .color-white {
      color: #fff !important;
  }`
                this.printByLodop(strHtmls, elStyle, 1, 958, 1524)
              }
            })
          })
        }
      },
      printByLodop(strHtml, bodyStyle, type, width, height) {
        var LODOP = getLodop() //调用getLodop获取LODOP对象
        LODOP.PRINT_INIT('')
        // LODOP.SET_ZOOM_MODE(LODOP.ZOOM_WIDTH, 100)
        // LODOP.SET_PRINT_SCALE(100)
        // LODOP.SET_PRINT_PAGESIZE(2)
        LODOP.SET_PRINT_PAGESIZE(type, width, height)
        LODOP.SET_PRINT_STYLEA(3, 'FontName', '微软雅黑')

        if (isArray(strHtml)) {
          strHtml.forEach((el, index) => {
            if (el.trim()) {
              el = `<style>${bodyStyle}</style><body>${el}</body>`
              console.log(el)
              LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', el)
              // const currentBlood = this.bloods[index]
              // const { id_out, id, product_code, abo_code, tube_number } =
              //   currentBlood
              // const arr = [
              //   { value: id_out, top: 0, left: 0, width: 155, height: 36 },
              //   { value: id, top: 95, left: 0, width: 155, height: 40 },
              //   {
              //     value: product_code,
              //     top: 0,
              //     left: 0,
              //     width: 155,
              //     height: 36,
              //   },
              //   { value: abo_code, top: 0, left: 0, width: 155, height: 36 },
              //   { value: tube_number, top: 0, left: 0, width: 155, height: 36 },
              //   { value: tube_number, top: 0, left: 0, width: 155, height: 36 },
              // ]
              // arr.forEach((item) => {
              //   const { value, top, left, width, height } = item
              //   LODOP.ADD_PRINT_BARCODE(top, left, width, height, '128A', value)
              // })

              if (index < strHtml.length - 1) {
                LODOP.NewPage() // 只在非最后一页添加新页面
              }
            }
          })
        } else {
          if (strHtml.trim()) {
            strHtml = `<style>${bodyStyle}</style><body>${strHtml}</body>`
            LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', strHtml)
          }
        }
        if (1 || this.systemSet.silent_preview) {
          LODOP.PREVIEW()
        } else {
          console.log('***********print***********')
          // LODOP.PRINT()
        }

        // 打印回调函数
        LODOP.On_Return = (TaskID, Value) => {
          // TaskID 任务的唯一标识符。在执行打印、预览等操作时，LODOP 会为每个操作分配一个唯一的任务 ID。通过这个 ID 可以区分不同的操作任务
          // Value 0打印成功 1打印失败
          if (+Value === 0) {
            console.log('打印成功')
            this.$baseEventBus.$emit('reload-router-view')
          } else {
            console.log('放弃打印')
            this.$baseEventBus.$emit('reload-router-view')
          }
        }
      },
      close() {
        this.doPrints()
        this.bloods = []
        this.$emit('getAll')
      },
    },
  }
</script>

<style lang="scss" scoped>
  @media print {
    @page {
      margin: 0 !important; /* 设置页边距为0 */
    }
  }
  #printArea {
    width: 306px;
    color: #111;
  }
  .t-l {
    width: 155px;
  }
  .t-r {
    width: 151px;
  }
  .b-c {
    width: 151px;
  }
  .font {
    &10 {
      font-size: 20px;
      transform: scale(0.5); /* 然后缩小至80% */
      transform-origin: 0 0; /* 可能需要指定缩放原点以确保准确缩放 */
    }
    &11 {
      font-size: 11px;
    }
    &12 {
      font-size: 12px;
    }
    &14 {
      font-size: 14px;
    }
    &16 {
      font-size: 16px;
    }
    &18 {
      font-size: 18px;
    }
    &20 {
      font-size: 20px;
    }
    &22 {
      font-size: 22px;
    }
    &24 {
      font-size: 24px;
    }
    &36 {
      font-size: 36px;
    }
    &40 {
      font-size: 40px;
    }
  }
  .mr {
    &4 {
      margin-right: 4px;
    }
    &6 {
      margin-right: 6px;
    }
    &8 {
      margin-right: 8px;
    }
    &10 {
      margin-right: 10px;
    }
    &12 {
      margin-right: 12px;
    }
  }
</style>
